// pages/chat/index.js
const app = getApp();
import {commonAPI} from '../../api/common/index'
import {$await} from '../../utils/util'
import runtime from '../../utils/runtime'
import face from '../../utils/emoji'
const face_online_path = "https://images.weserv.nl/?url=https://img001.cbct.cn/image/face/"
Component({
  properties:{
    atInfo:{ // 点击用户列表时传入的某个用户信息，此参数只用来接受要@的用户信息，无此需求可不传
      type:Object,
      value:{}
    },
    number:{ // 直播间number ，不发消息时无需传此参数
      type:[Number,String],
      value:''
    },
    roomid:{ // 融云加入聊天室时的roomid ，必传！！
      type:[Number,String],
      value:'',
      
    },
  },
   observers:{
    'atInfo'(n){
      if(Object.keys(n).length>0){
        this.setAtMsg(n)
      }
    },
    'roomid'(new_roomid){
      if(new_roomid){
        wx.join_room(new_roomid)
      }
    },
  },

  /**
   * 页面的初始数据
   */
  data: {
    // 表情包
    faceList:face.map(item => ({...item,url:`${face_online_path}${item.url}`})),
    inputBottom:0,
    _keyboardShow:false,
    emoji:false,
    focus:false,
    at_jsonUser:[],
    // showUserList:false,
    msgContent:'',// 消息内容
    conversationList:[], // 消息列表
    hostList:[],
    closeDownload:true,
    chatAreaHeight:0, // 聊天区域的高
    toView:'scroll0',//滚动ID
    //系统消息map
    systemMsgMap:{
      'enableLink':'主持人开启了连线'
    },
    personName:'',// 某人进入直播间
    switchStreamDates:{},
  },
  // 组件生命周期
  lifetimes: {
    // 在组件实例进入页面节点树时执行
    created() {
      this.timer = null
      this.userInfo = wx.getStorageSync('userInfo')
      // 监听系统消息
      wx.event.on('cb_room',(data) => this.cbRoom(data))
      // 监听文本消息
      wx.event.on('cb_message',(data) => this.cbMessage(data))
    },
    attached() {
      wx.nextTick(()=>{
        let query = this.createSelectorQuery().in(this)
        query.select('.chat').boundingClientRect()
        query.select('.send_msg').boundingClientRect()
        query.exec((rect)=>{
          let chat = rect[0].height
          let input = rect[1].height
          let chatAreaHeight = (chat - input).toFixed(2)
          this.setData({chatAreaHeight})
          wx.setStorageSync('shopH', chat)
        })
      })
    },
    // 在组件实例被从页面节点树移除时执行
    detached() {
      wx.event.off('cb_room')
      wx.event.off('cb_message')
    },
  },
  methods: {
    // 系统消息
    cbRoom(data){
      const {conversationList,systemMsgMap} = this.data
      data.forEach(item =>{
        if(item.action === 'enter'){
          this.setData({personName:item.nickname})
          if(this.timer){
            clearTimeout(this.timer)
          }
          this.timer = setTimeout(() => {
            this.setData({personName:''})
            this.timer = null
          }, 5000)
        }
        const showSystem = systemMsgMap.hasOwnProperty(item.action)
        conversationList.push({...item,showSystem})
        this.setData({
          toView:'scroll'+String(conversationList.length-1),
          conversationList
        })
      })
    },
    // 文本消息
    cbMessage(data){
      const {conversationList} = this.data
      const formatData = this.msgType(data)
      conversationList.push(formatData)
      this.setData({
        toView:'scroll'+String(conversationList.length-1),
        conversationList
      })
    },
    onkeyboardHeightChange(e) {
      const {height} = e.detail
      wx.nextTick(()=>{
        this.setData({
          inputBottom: height
        })
      })
    },
    bindblur(e){
      this.data._keyboardShow = false
      wx.nextTick(()=>{
        setTimeout(() => {
          if(!this.data.emoji){
            this.setData({
              focus:false
            },()=>{
              this.setData({inputBottom:0})
            })
          }
        }, 0);
      })
    },
    bindfocus(e){
      this.data._keyboardShow = true
      this.setData({
        emoji:false,
        focus:true
        // inputBottom:e.detail.height
      })
    },
    // 添加表情到输入框
    setEmoji({detail}){
      let {msgContent} = this.data
      msgContent+=detail
      this.setData({msgContent})
    },
    // 显示表情组件
    showEmoji(){
      this.setData({emoji:this.data._keyboardShow || !this.data.emoji})
      wx.nextTick(()=>{
        let query = this.createSelectorQuery().in(this)
        query.select('#emoji').boundingClientRect()
        query.exec((rect)=>{
          this.setData({
            inputBottom:rect[0].height,
            focus:false
          })
        })
      })
    },
    // 删除表情
    deleteEmoji() {
      const pos = Number(this.data.msgContent.length)
      const comment = this.data.msgContent
      let result = '',
        cursor = 0
  
      let emojiLen = 6
      let startPos = pos - emojiLen
      if (startPos < 0) {
        startPos = 0
        emojiLen = pos
      }
      const str = comment.slice(startPos, pos)
      const matchs = str.match(/\[([\u4e00-\u9fa5\w]+)\]$/g)
      // 删除表情
      if (matchs) {
        const rawName = matchs[0]
        const left = emojiLen - rawName.length
        const emojiNames = this.data.faceList.map(item => (item.content))
        if (emojiNames.indexOf(rawName) >= 0) {
          const replace = str.replace(rawName, '')
          result = comment.slice(0, startPos) + replace + comment.slice(pos)
          cursor = startPos + left
        }
        // 删除字符
      } else {
        let endPos = pos - 1
        if (endPos < 0) endPos = 0
        const prefix = comment.slice(0, endPos)
        const suffix = comment.slice(pos)
        result = prefix + suffix
        cursor = endPos
      }
      this.setData({
        msgContent: result,
        // cursor: cursor
      })
    },
    // 判断@的用户是不是自己
    isSelf(user){
      if(this.userInfo.user_id == user.uid){
        wx.showToast({
          icon:'none',
          title: '不能@自己',
          duration: 2000
        })
        return false
      }
      return true
    },
    // 设置@消息
    setAtMsg(msg,at = ''){
      let {msgContent,at_jsonUser} = this.data
        msgContent = `${msgContent}${at}${msg.nickname} `
        at_jsonUser.push({number:msg.number?msg.number:msg.uid,nickname:msg.nickname})
        this.setData({
          msgContent,
          at_jsonUser
        })
        wx.nextTick(()=>{
          this.setData({focus:true})
        })
    },
    // 用户点击某个消息获取@消息
    getAtMsg({currentTarget:{dataset:{atmsg}}}){
      if(this.isSelf(atmsg)){
        this.setAtMsg(atmsg,'@')
      }
    },
    bindinput({detail}){
      let value = detail.value
      if(value.indexOf('@')!= '-1'){
        let length = value.split('@').length;
        if(value.split('@')[length-1] == ''){
          this.setData({focus:false})
          wx.nextTick(()=>{
            this.triggerEvent('showAtlist', true)
          })
        }
    }
    },
    // 弹窗关闭
    downloadStatus(e){
      const {dataset:{status}} = e.target
      this.setData({closeDownload:status})
    },
    onShare(){
      wx.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline'],
        success:()=>{
          console.log(111)
        }
      })
    },
    download(){
      wx.navigateTo({
        url: '/pages/webview/webview?webURL=http://channels.h5.cbct.cn/downloadPage',
      })
      this.setData({closeDownload:true})
    },
    // 发消息
    async sendMsg({detail:{value}}){
      if(!this.userInfo.token || this.userInfo.token === 'TOKEN'){
        return wx.navigateTo({
          url:'/pages/login/login'
        })
      } 
      const {at_jsonUser} = this.data
      let api = null
      let params = {
        number:this.data.number,
      }
      if(value.indexOf('@')!= -1){ // @消息
        api = commonAPI.sendatMsg
        let at_json = {
          content:value,
          users:at_jsonUser
        }
        params = {
          ...params,
          content:value,
          at_json:JSON.stringify(at_json)
        }
      }else{ // 普通消息
        api = commonAPI.sendMsg
        params = {
          ...params,
          comment:value,
          flag:1
        }
      }
      const [err,res] = await $await(api({...params}))
      if(res){
        this.setData({msgContent:''})
      }
    },
    // 文本消息处理
    msgType(msg){
      const {action} = msg
      let newMsg = {}
      switch (action) {
        case 'pub_chat': // 普通消息
          newMsg = msg
          break;
        case 'chat_at_msg': // @消息
          let parseData = JSON.parse(msg.atJson)
          let users = parseData.users
          users.forEach(item =>{
            msg.content = msg.content.replace(
              new RegExp(`@${item.nickname}`,'g'),
              `<span style="color:rgba(255,183,53,.8);font-size:28rpx;">@${item.nickname}</span>`
              )
          })
          newMsg = msg
          break;
      
        default:
          newMsg = msg
          break;
      }
      // 表情处理
      this.data.faceList.forEach((item)=>{
        if(newMsg.content.indexOf(item.content)!=-1){
          newMsg.content = newMsg.content.replaceAll(
            item.content,
            `<img class="face_msg" src="${item.url}"/>`
            )
        }
      })
      return newMsg
    },
  }
})